﻿using CloudApiServer.Services;
using log4net.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows.Forms;
using System.Configuration;
using System.Reflection;
using MySqlX.XDevAPI;
using System.IO;
using System.Runtime.Remoting.Contexts;
using CloudApiServer.helper;
using Newtonsoft.Json;

namespace CloudApiServer
{
    /// <summary>
    /// 控制台首页
    /// </summary>
    public partial class Mainform : Form
    {
        /// <summary>
        /// http服务
        /// </summary>
        private HttpService _http;

        public Mainform()
        {
            InitializeComponent();
            this.Text = $"{Text} {SystemInfo.Version} ({SystemInfo.Versiontime})" ;
            this.notifyIcon_main.Text  = $"{Text}";
            this.StartButton.Enabled = true;
            this.CloseButton.Enabled = false;
            PublicMethod.RefreshConfiguration();
            this.Resize += new EventHandler(MainFrom_Resize);
            LogDelete();
            try
            {
                if (ApiDatainfo.stateRedis)
                {
                    RedisHelper.Initialize(ApiDatainfo.redisUrl,ApiDatainfo.redisDb); 
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"Redis数据库连接失败！错误内容：{ex.Message} 异常类型：{ex.GetType()} 异常堆栈{ex.StackTrace}");
                MessageBox.Show($"在启用了Redis配置下连接Redis连接失败！部分使用Redis功能将不可用！请检查Redis服务情况或调整Redis配置信息！\r\n错误内容：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }
        /// <summary>
        /// 窗体加载 ui页面参数初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainFrom_Load(object sender, EventArgs e)
        {

            this.comboBox_DatabaseServer.Text = ApiDatainfo.mysqlUrl;
            this.numericUpDown_DatabasePost.Value = int.Parse(ApiDatainfo.mysqlPost);
            this.comboBox_redisUrl.Text = ApiDatainfo.redisUrl;
            this.numericUpDown_redisdbindex.Value = ApiDatainfo.redisDb;
            this.checkBox_OnOffRedisState.Checked = ApiDatainfo.stateRedis;
            this.numericUpDown_redisexpirationtime.Value = ApiDatainfo.redisExpirationtime;
            this.PortNum.Value = SystemInfo.localurlpost;

            this.checkBox_OnOffInfoLogDelete.Checked = LogDeleteSettings.InfoLogDeleteActive;
            this.checkBox_OnOffErrorLogDelete.Checked = LogDeleteSettings.ErrorLogDeleteActive;
            this.numericUpDown_InfoLogDay.Value = LogDeleteSettings.InfoLogDeleteDay;
            this.numericUpDown_ErrorLogDay.Value = LogDeleteSettings.ErrorLogDeleteDay;

            this.checkBox_OnOffDrugStroeSettleDelay.Checked = FsiDatainfo.stateDrugStroeSettleDelay;
            this.checkBox_OnOffDrugStroeSettlePreDelay.Checked = FsiDatainfo.stateDrugStroeSettlePreDelay;
            this.numericUpDown_DrugStroeSettleDelayTime.Value = FsiDatainfo.drugStroeSettleDelayTime;
            this.checkBox_OnOffDrugStroeSettleReturnError.Checked = FsiDatainfo.stateDrugStroeSettleReturnError;
            this.checkBox_OnOffRevsMethodDataVerify.Checked = FsiDatainfo.stateRevsMethodDataVerify;

            this.checkBox_OnOffFsiApi.Checked = FsiDatainfo.stateFsiApi;
            this.checkBox_OnOffNeusJiangsuApi.Checked = FsiDatainfo.stateNeusJiangsuApi;
            this.checkBox_OnOffSignno.Checked = FsiDatainfo.statesignon;
            this.checkBox_OnOffFsiEpcApi.Checked = FsiDatainfo.stateFsiEpcApi;
            this.checkBox_OnOffFsiCfcApi.Checked = FsiDatainfo.stateFsiCfcApi;
            this.checkBox_OnOffShandongbinzhouApi.Checked = FsiDatainfo.stateShandongBinzhouApi;
            this.checkBox_OnOffShandongDarewayApi.Checked = FsiDatainfo.stateShandongDarewayApi;
            this.checkBox_OnOffShandongJxcApi.Checked = FsiDatainfo.stateShandongJxcApi;
            this.checkBox_OnOffLocalApiInInternal.Checked = FsiDatainfo.stateLocalApiInInternal;
        }
        /// <summary>
        /// 托盘图标
        /// </summary>
        /// <param name="time"></param>
        /// <param name="title"></param>
        /// <param name="info"></param>
        /// <param name="type"></param>
        public void notifyIcon(int time, string title, string info, int type)
        {
            switch (type)
            {
                case 1:
                    notifyIcon_main.ShowBalloonTip(time, title, info, ToolTipIcon.Info);
                    break;
                case 2:
                    notifyIcon_main.ShowBalloonTip(time, title, info, ToolTipIcon.Error);
                    break;
                default:
                    MessageBox.Show("调用未经定义的托盘图标通知类型！请检查代码,当前传入：" + type, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
            }
        }


        /// <summary>
        /// 开启http服务触发
        /// </summary>
        private async void StartButton_Click(object sender, EventArgs e)
        {
            try
            {
                var port = Convert.ToInt32(this.PortNum.Value);
                SystemInfo.localurlpost = Convert.ToInt32(this.PortNum.Value);
                _http = new HttpService(port);

                await _http.StartHttpServer();
                LogHelper.Info("Api服务开启，服务端端口：" + port);
                //MessageBox.Show("API服务已开启", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.StartButton.Enabled = false;
                this.PortNum.Enabled = false;
                this.CloseButton.Enabled = true;
            }
            catch (AggregateException ex)
            {
                if (ex.Flatten().InnerExceptions.Any(ex => ex is AddressAccessDeniedException))
                {
                    LogHelper.Error($"Api服务访问被拒绝");
                    MessageBox.Show($"API服务访问被拒绝，请使用管理员运行控制台应用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"Api服务开启失败！错误内容：{ex.Message} 异常类型：{ex.GetType()} 异常堆栈{ex.StackTrace}");
                MessageBox.Show($"Api服务开启失败！错误内容：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 关闭http服务触发
        /// </summary>
        private async void CloseButton_Click(object sender, EventArgs e)
        {
            try
            {
                await _http.CloseHttpServer();
                _http.Dispose();
                LogHelper.Info("Api服务已关闭");
                //MessageBox.Show("API服务已关闭", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.StartButton.Enabled = true;
                this.PortNum.Enabled = true;
                this.CloseButton.Enabled = false;
                
            }
            catch (Exception ex)
            {
                LogHelper.Error($"Api服务关闭失败！错误内容：{ex.Message} 异常类型：{ex.GetType()} 异常堆栈{ex.StackTrace}");
                MessageBox.Show($"Api服务关闭失败！错误内容：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void button_SaveDatabaseInfo_Click(object sender, EventArgs e)
        {
            LogHelper.Info("----------开始保存数据库参数配置----------");
            try
            {
                if (checkBox_OnOffRedisState.Checked)
                {
                    RedisHelper.Initialize(comboBox_redisUrl.Text,int.Parse(numericUpDown_redisdbindex.Text)); 
                    LogHelper.Info("Redis数据库初始化成功！");
                }
                ApiDatainfo.redisUrl = this.comboBox_redisUrl.Text;
                PublicMethod.WriteInI("ApiDatainfo", "redisUrl", comboBox_redisUrl.Text);
                ApiDatainfo.redisDb = Convert.ToInt32(this.numericUpDown_redisdbindex.Text);
                PublicMethod.WriteInI("ApiDatainfo", "redisDb", numericUpDown_redisdbindex.Text);
            
                ApiDatainfo.stateRedis = this.checkBox_OnOffRedisState.Checked;
                PublicMethod.WriteInI("ApiDatainfo", "stateRedis", checkBox_OnOffRedisState.Checked.ToString());
                ApiDatainfo.redisExpirationtime = Convert.ToInt32(this.numericUpDown_redisexpirationtime.Text);
                PublicMethod.WriteInI("ApiDatainfo", "redisExpirationtime", numericUpDown_redisexpirationtime.Text);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"Redis数据库连接失败！错误内容：{ex.Message} 异常类型：{ex.GetType()} 异常堆栈{ex.StackTrace}");
                MessageBox.Show($"Redis数据库连接失败！错误内容：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={comboBox_DatabaseServer.Text};Port={numericUpDown_DatabasePost.Text};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                string query = "select 1"; 
                _ = MySqlHelper.ExecuteNonQueryAsync(connectionString, query);
                LogHelper.Info("Mysql数据库连接成功！");
                ApiDatainfo.mysqlUrl = this.comboBox_DatabaseServer.Text;
                PublicMethod.WriteInI("ApiDatainfo", "mysqlUrl", comboBox_DatabaseServer.Text);
                ApiDatainfo.mysqlPost = this.numericUpDown_DatabasePost.Text;
                PublicMethod.WriteInI("ApiDatainfo", "mysqlPost", numericUpDown_DatabasePost.Text);

            }
            catch (Exception ex)
            {
                LogHelper.Error($"Mysql数据库连接失败！错误内容：{ex.Message} 异常类型：{ex.GetType()} 异常堆栈{ex.StackTrace}");
                MessageBox.Show($"Mysql数据库连接失败！错误内容：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            LogHelper.Info("----------结束保存数据库参数配置----------");
            MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        private void notifyIcon_main_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void MainFrom_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                //isHidden = true; // 设置标志，表示窗体已隐藏  
            }
        }

        private void button_SaveFsiInfo_Click(object sender, EventArgs e)
        {

            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    LogHelper.Info("----------开始保存医保控制参数配置----------");
                    FsiDatainfo.stateFsiApi = checkBox_OnOffFsiApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateFsiApi", checkBox_OnOffFsiApi.Checked.ToString());
                    FsiDatainfo.stateNeusJiangsuApi = checkBox_OnOffNeusJiangsuApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateNeusJiangsuApi", checkBox_OnOffNeusJiangsuApi.Checked.ToString());
                    FsiDatainfo.statesignon = checkBox_OnOffSignno.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "statesignon", checkBox_OnOffSignno.Checked.ToString());
                    FsiDatainfo.stateFsiEpcApi=checkBox_OnOffFsiEpcApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateFsiEpcApi", checkBox_OnOffFsiEpcApi.Checked.ToString());
                    FsiDatainfo.stateFsiCfcApi=checkBox_OnOffFsiCfcApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateFsiCfcApi", checkBox_OnOffFsiCfcApi.Checked.ToString());
                    
                    FsiDatainfo.stateShandongBinzhouApi=checkBox_OnOffShandongbinzhouApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateShandongBinzhouApi", checkBox_OnOffShandongbinzhouApi.Checked.ToString());
                    FsiDatainfo.stateShandongDarewayApi=checkBox_OnOffShandongDarewayApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateShandongDarewayApi", checkBox_OnOffShandongDarewayApi.Checked.ToString());
                    FsiDatainfo.stateShandongJxcApi= checkBox_OnOffShandongJxcApi.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateShandongJxcApi", checkBox_OnOffShandongJxcApi.Checked.ToString());
                    FsiDatainfo.stateLocalApiInInternal = checkBox_OnOffLocalApiInInternal.Checked;
                    PublicMethod.WriteInI("FsiDatainfo", "stateLocalApiInInternal", checkBox_OnOffLocalApiInInternal.Checked.ToString());
                    LogHelper.Info("----------结束保存医保控制参数配置----------");

                    scope.Complete();
                    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存失败！错误内容:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void button_SaveLogDelete_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.Info("----------开始保存日志删除参数配置----------");
                LogDeleteSettings.InfoLogDeleteActive = checkBox_OnOffInfoLogDelete.Checked;
                PublicMethod.WriteInI("SystemInfo", "InfoLogDeleteActive", checkBox_OnOffInfoLogDelete.Checked.ToString());

                LogDeleteSettings.ErrorLogDeleteActive = checkBox_OnOffErrorLogDelete.Checked;
                PublicMethod.WriteInI("SystemInfo", "ErrorLogDeleteActive", checkBox_OnOffErrorLogDelete.Checked.ToString());

                LogDeleteSettings.InfoLogDeleteDay = (int)this.numericUpDown_InfoLogDay.Value;
                PublicMethod.WriteInI("SystemInfo", "InfoLogDeleteDay", numericUpDown_InfoLogDay.Text);

                LogDeleteSettings.ErrorLogDeleteDay = (int)this.numericUpDown_ErrorLogDay.Value;
                PublicMethod.WriteInI("SystemInfo", "ErrorLogDeleteDay", numericUpDown_ErrorLogDay.Text);


                LogHelper.Info("----------结束保存日志删除参数配置----------");
                MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败！错误内容:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void button_DrugStroeSettleDelay_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.Info("----------开始保存结算接口延迟配置参数----------");
                FsiDatainfo.stateDrugStroeSettleDelay = checkBox_OnOffDrugStroeSettleDelay.Checked;
                PublicMethod.WriteInI("FsiDatainfo", "stateDrugStroeSettleDelay", checkBox_OnOffDrugStroeSettleDelay.Checked.ToString());
                
                FsiDatainfo.stateDrugStroeSettlePreDelay= checkBox_OnOffDrugStroeSettlePreDelay.Checked;
                PublicMethod.WriteInI("FsiDatainfo", "stateDrugStroeSettlePreDelay", checkBox_OnOffDrugStroeSettlePreDelay.Checked.ToString());
                
                FsiDatainfo.stateDrugStroeSettleReturnError = checkBox_OnOffDrugStroeSettleReturnError.Checked;
                PublicMethod.WriteInI("FsiDatainfo", "stateDrugStroeSettleReturnError", checkBox_OnOffDrugStroeSettleReturnError.Checked.ToString());
                
                FsiDatainfo.stateRevsMethodDataVerify = checkBox_OnOffRevsMethodDataVerify.Checked;
                PublicMethod.WriteInI("FsiDatainfo", "stateRevsMethodDataVerify", checkBox_OnOffRevsMethodDataVerify.Checked.ToString());
                
                
                FsiDatainfo.drugStroeSettleDelayTime = (int)this.numericUpDown_DrugStroeSettleDelayTime.Value;
                PublicMethod.WriteInI("FsiDatainfo", "drugStroeSettleDelayTime", numericUpDown_DrugStroeSettleDelayTime.Text);

                LogHelper.Info("----------结束保存日志删除参数配置----------");
                MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败！错误内容:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 启动时过往日志删除
        /// </summary>
        public void LogDelete()
        {
            try
            {
                LogHelper.Info($"[LogDelete]信息日志删除功能启用状态：{LogDeleteSettings.InfoLogDeleteActive} 信息日志删除天数：{LogDeleteSettings.InfoLogDeleteDay} 错误日志删除功能启用状态：{LogDeleteSettings.ErrorLogDeleteActive} 错误日志删除天数：{LogDeleteSettings.ErrorLogDeleteDay}");
                string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
                if (!Directory.Exists(logDirectory))
                {
                    LogHelper.Info($"[LogDelete]日志路径【{logDirectory}】不存在！");
                    return;
                }

                if (LogDeleteSettings.InfoLogDeleteActive == true)
                {
                    // 获取信息日志
                    string[] logFiles = Directory.GetFiles(logDirectory, "Info_*.log");
                    foreach (string file in logFiles)
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        DateTime fileLastWriteTime = fileInfo.LastWriteTime;

                        if (DateTime.Now - fileLastWriteTime >
                            TimeSpan.FromDays(LogDeleteSettings.InfoLogDeleteDay))
                        {
                            fileInfo.Delete();
                            LogHelper.Info($"[LogDelete]已删除信息日志文件: {file}");
                        }
                    }
                }

                if (LogDeleteSettings.ErrorLogDeleteActive == true)
                {
                    // 获取信息日志
                    string[] logFiles = Directory.GetFiles(logDirectory, "Error_*.log");
                    foreach (string file in logFiles)
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        DateTime fileLastWriteTime = fileInfo.LastWriteTime;

                        if (DateTime.Now - fileLastWriteTime >
                            TimeSpan.FromDays(LogDeleteSettings.ErrorLogDeleteDay))
                        {
                            fileInfo.Delete();
                            LogHelper.Info($"[LogDelete]已删除错误日志文件: {file}");
                        }
                    }
                }

                LogHelper.Info($"[LogDelete]删除日志处理结束！");
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[LogHelper.LogDeleteJob]删除日志处理失败！错误内容：{ex.Message}");
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button_ShowFsiSetting_Click(object sender, EventArgs e)
        {
            Frm_FsiSetting f1 = new Frm_FsiSetting();
            f1.ShowDialog();
        }

        private void button_test_Click(object sender, EventArgs e)
        {
            try
            {
                string sKey = "o9WSpDrG7oec+5U8NeedsnxJTyE=";
                string initInfoEncrypted = "jItK0orRp8QxLdndDzoo7iqlnWccE20zmJd17fIMSWs=";

                string decrypted = TripleDesCryptoHelper.DecryptInitInfo(initInfoEncrypted, sKey);
                Console.WriteLine("3DES 解密结果: " + decrypted);
                MessageBox.Show("3DES 解密结果: " + decrypted);
                
                /*
                // 解密
                string decrypted = AesCryptoHelper.DecryptInitInfo(initInfoEncrypted, aKey);
                Console.WriteLine("解密结果: "); // 可能输出 "8C78D7B505EC|20250514070223"
                Console.WriteLine(decrypted); // 可能输出 "8C78D7B505EC|20250514070223"

                // 加密
                string newInitInfo = AesCryptoHelper.EncryptInitInfo("20250514070223755", aKey);
                Console.WriteLine("加密结果: " + newInitInfo); // 类似 "4mvBAPRXHsUzVO+W0KdzH2NB7xU5mbm23BBjh86DjXo="
                */
            }
            catch (Exception ex)
            {
                MessageBox.Show($"测试失败！错误内容:{ex.Message}\r\n异常堆栈：{ex.StackTrace}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
            }
        }
    }
 }
